layui.use(['form', 'table', 'layer', 'jquery'], function () {
    var $ = layui.jquery,
        form = layui.form,
        table = layui.table,
        layer = layui.layer;
    var cis = $("#cis").val();
    table.render({
        elem: '#currentTableId',
        id: 'clientTable',
        url: '/api/Client/findClientPage',
        where: {"cis": cis},
        request: {
            pageName: 'current' //页码的参数名称，默认：page
            , limitName: 'size' //每页数据量的参数名，默认：limit
        },
        cols: [[
            {field: 'cid', title: '编号', sort: true},
            {field: 'cname', title: '客户姓名'},
            {field: 'ctel', title: '联系方式'},
            {field: 'caddress', title: '地址'},
            {field: 'cis', title: '备注'},
            {title: '操作', minWidth: 50, templet: '#currentTableBar', fixed: "right", align: "center"}
        ]],
        limits: [5, 10, 15, 20, 50, 100],
        limit: 5,
        page: true
    });
    // 重载表单
    let reloadTable = (param) => {
        table.reload('clientTable', {
            url: '/api/Client/select'
            , where: {
                cid: param.cid,
                eid: param.eid,
                pid: param.pid

            }
        });
    };

    $(() => {
        //初始化部门名称数据
        $.get({
            url: "/api/department/partList", success: (resp) => {
                resp.forEach(r => {
                    $("#part").append("<option value='" + r.pid + "'>" + r.pname + "</option>");
                });
                form.render('select');
            }, dataType: "json"
        });
    });
    //部门名称select监听器
    form.on('select(partFilter)', (data) => {
        //部门id
        let pid = $('#part option:selected').val();
        if (!!pid) {
            $('.e-class').remove();
            $('.c-class').remove();
            $.get({
                url: "/api/emp/" + pid + "", success: (resp) => {
                    resp.forEach(r => {
                        $("#emp").append("<option class='e-class' value='" + r.eid + "'>" + r.etruename + "</option>");
                    });
                    form.render('select');
                }, dataType: "json"
            });
            reloadTable({'pid': pid, 'eid': '', 'cid': ''});
        }
    });
    //员工名称select监听器
    form.on('select(empFilter)', (data) => {
        //员工id
        let eid = $('#emp option:selected').val();
        let pid = $('#part option:selected').val();
        //根据员工id查询客户列表
        if (!!eid) {
            $('.c-class').remove();
            $.get({
                url: "/api/Client/" + eid, success: (resp) => {
                    resp.forEach(r => {
                        $("#client").append("<option class='c-class' value='" + r.cid + "'>" + r.cname + "</option>");
                    });
                    form.render('select');
                }, dataType: "json"
            });
            reloadTable({'pid': pid, 'eid': eid, 'cid': ''});
        }
    });

    form.on('select(clientFilter)', (data) => {
        //员工id
        let cid = $('#client option:selected').val();
        let eid = $('#emp option:selected').val();
        let pid = $('#part option:selected').val();
        //根据乘客和id查询客户列表
        reloadTable({'pid': pid, 'eid': eid, 'cid': cid});
        form.render('select');
    });

    // 查询存在的客户信息
    $("#order-btn1").click(function () {
        $("#currentTableBar").html(`<a class="layui-btn layui-btn-xs data-count-edit layui-bg-black" lay-event="edit" id="update" >修改</a><a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>`
        )
        var table = table = layui.table;
        var cis = $("#cis").val();
        axios.get('/api/Client/selectAll')
            .then(function (response) {
            })
        table.reload(
            'clientTable', {
                where: {"cis": 1}
                , page: {
                    curr: 1
                }
            }
        )

    });

    //查询已删除客户的信息
    $("#order-btn3").click(function () {
        $("#currentTableBar").html(`<a class="" ></a>`)
        var table = table = layui.table;
        var cis = $("#cis").val();
        axios.get('/api/Client/selectAll')
            .then(function (response) {

            })
        table.reload(
            'clientTable', {
                where: {"cis": 0}
                , page: {
                    curr: 1
                }
            }
        )
    });


    //添加客户
    $("#order-btn2").click(function () {
        layer.open({
            type: 2
            , skin: "demo-class"
            , id: 'layerDemo'//防止重复弹出
            , content: 'add.html'
            , area: ['400px', '470px']
            ,scrollbar: false
            , btn: '添加'
            , btnAlign: 'c' //按钮居中
            , shade: [0.3, '#2F4056']
            , resize: false
            , title: "添加客户"
            , yes: function (index) {
                var data = window['layui-layer-iframe' + index].aaa();//获取add.html值
                if (data.cname == "") {
                    layer.msg("请输入客户姓名");
                    return -1;
                }
                if (data.ctel == "") {
                    layer.msg("请输入客户联系电话");
                    return -1;
                }
                if (data.caddress == "") {
                    layer.msg("请输入客户地址");
                    return -1;
                }
                if (data.cremark == "") {
                    layer.msg("请输入客户备注");
                    return -1;
                }
                console.log(data);
                axios.get('/api/Client/insert', {
                    params: {
                        "cName": data.cname,
                        "cTel": data.ctel,
                        "cAddress": data.caddress,
                        "cIs": data.cremark,
                        "pId": data.part,
                        "eId": data.emp
                    }
                })
                    .then(function (response) {
                        alert("添加成功");
                    })
                    .catch(function (error) {

                    }).then(function (index) {
                    var table = layui.table;
                    table.reload('clientTable', {
                            page: {curr: 1}
                        }
                    );
                });
                layer.close(index);
            }
        });
    });

    // 监听删除操作
    table.on('tool(currentTableFilter)', function (obj) {
        var data = obj.data;
        if (obj.event === 'delete') {
            layer.confirm('确定要删除吗', function (index) {
                axios.get('/api/Client/updatecIsBycId', {
                    params: {
                        cId: data.cid,
                        cIs: data.cis,
                    }
                })
                    .then(function (response) {
                        if (response.data.ct == 1) {
                            alert("删除失败，该客户下存在订单");
                        } else {
                            obj.del();
                            alert("删除成功");
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    })
                    .then(function (index) {
                    });
                layer.close(index);

            });
            //修改操作
        } else if (obj.event === 'edit') {
            layer.open({
                type: 2
                , skin: "demo-class"
                , id: 'layerDemo'//防止重复弹出
                , content: 'update_client.html'
                , area: ['500px', '300px']
                , btn: '修改'
                , btnAlign: 'c' //按钮居中
                , shade: [0.3, '#2F4056']
                , resize: false
                , title: "修改客户"
                , success: function (layero, index) {
                    var body = layer.getChildFrame('body', index);
                    body.contents().find('#cid').val(data.cid);
                    body.contents().find('#cname').val(data.cname);
                    body.contents().find('#ctel').val(data.ctel);
                    body.contents().find('#caddress').val(data.caddress);
                    body.contents().find('#cremark').val(data.cis);
                    form.render();
                }
                , yes: function (index) {
                    var data = window['layui-layer-iframe' + index].getValues();
                    axios.get('/api/Client/update',
                        {
                            params: {
                                "cId": data.cid,
                                "cName": data.cname,
                                "cTel": data.ctel,
                                "cAddress": data.caddress,
                                "cIs": data.cremark
                            }
                        })
                        .then(function (response) {
                            layer.msg("修改成功！");
                        })
                        .catch(function (error) {
                        })
                        .then(function (index) {
                            table.reload('clientTable', {
                                    page: {curr: 1}
                                }
                            );
                        });
                    layer.close(index);
                }
            })
        }
    })

});